package org.aoao.controller;

import org.aoao.utils.FileReadOrWrite;
import org.aoao.utils.HexTrans;
import org.aoao.utils.MyMsgDigest;
import org.aoao.utils.MyRSA;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

@Controller
public class FileController {

    @RequestMapping("/uploadFile")
    public String uploadFile(HttpSession session, HttpServletRequest request, @RequestParam("file1")MultipartFile file1){
        // 将前端传递过来的文件 存在指定目录下，文件名为file1.doc
        String filePath=FileReadOrWrite.saveFiles(request,file1,"file1.doc");
        // 获取文件内容字符串
        String content=FileReadOrWrite.getDocString(filePath);
        session.setAttribute("content1",content);
        // 将字符串数据转化为字节数组
        byte[] data= content.getBytes();
        // 对字节数组进行 消息摘要
        byte[] digest= MyMsgDigest.digestByteMD5(data,"md5");
        // 对消息摘要 进行RSA数字签名
        MyRSA myRSA=new MyRSA();
        // 将公钥和签名信息存入会话中
        session.setAttribute("publicKey",myRSA.getPublicKey());
        session.setAttribute("signData",myRSA.getSignData(digest));
        // 跳转到 check视图
        return "check";
    }

    @RequestMapping("/checkFile")
    public String checkFile(HttpSession session,HttpServletRequest request, @RequestParam("file")MultipartFile file1){
        // 将前端传递过来的文件 存在指定目录下，文件名为file2.doc
        String filePath=FileReadOrWrite.saveFiles(request,file1,"file2.doc");
        // 读取文件
        String content=FileReadOrWrite.getDocString(filePath);
//        request.setAttribute("result",content);
        // 将字符串数据转化为字节数组
        byte[] data= content.getBytes();
        // 对字节数组进行 消息摘要
        byte[] digest= MyMsgDigest.digestByteMD5(data,"md5");
        // 用RSA算法对消息摘要进行验证
        MyRSA myRSA=new MyRSA();
        // 获取 会话中的公钥
        PublicKey publicKey= (PublicKey) session.getAttribute("publicKey");
        System.out.println(publicKey);
        // 获取 会话中的签名数据
        byte[] signData= (byte[]) session.getAttribute("signData");
        // 将验证结果 存入request 中
        request.setAttribute("result",myRSA.verifySign(signData,digest,publicKey));
        // 将 两个文件的 摘要信息存入 request中
        request.setAttribute("content1",(String) session.getAttribute("content1"));
        request.setAttribute("content2",content);
        // 找到指定视图
        return "result";
    }
}
